import React, { useState } from 'react';
import { Modal, Button, Input, Form, message } from 'antd';
import { useTranslation } from 'react-i18next';
import { sha256 } from 'js-sha256';
import userService from '@/api/services/userService';
import { useUserInfo } from '@/store/userStore';

interface ResetPasswordModalProps {
  visible: boolean;
  onCancel: () => void;
}

const ResetPasswordModal: React.FC<ResetPasswordModalProps> = ({
  visible,
  onCancel,
}) => {
  const [form] = Form.useForm();
  const { t } = useTranslation();
  // const { username, id: userId } = useUserInfo();
  const userInfo = useUserInfo();
  const [submitting, setSubmitting] = useState(false);

  const handleSubmit = async (values: any) => {
    if (values.newPassword === values.originPassword) {
      message.error(t('page.user.password.not_same_as_origin'));
      return;
    }
    if (values.newPassword !== values.confirmPassword) {
      message.error(t('page.user.password.confirm_not_match'));
      return;
    }

    // 检查密码强度
    const checkPasswordStrength = (password: string) => {
      const hasUpper = /[A-Z]/.test(password);
      const hasLower = /[a-z]/.test(password);
      const hasDigit = /[0-9]/.test(password);
      const hasSpecial = /[!@#$%^&*()_+\-=${}';:"\\|,.<>/?]/.test(password);
      const conditionsMet = [hasUpper, hasLower, hasDigit, hasSpecial].filter(Boolean).length;
      return password.length >= 8 && conditionsMet >= 3;
    };

    if (!userInfo._id) {
      console.log(userInfo);
      message.error(t('page.user.password.login_first'));
      return;
    }

    if (!checkPasswordStrength(values.newPassword)) {
      message.error(t('page.user.password.strength_requirement'));
      return;
    }

    try {
      setSubmitting(true);
      const hashStr = (str: string) => sha256(str);
      await userService.updatePassword(
        userInfo._id,
        {
          new_password: hashStr(values.newPassword),
          origin_password: hashStr(values.originPassword),
        });
      message.success(t('page.user.password.modify_success'));
      form.resetFields();
      onCancel();
    } catch (error) {
      console.error(t('page.user.password.modify_failed'), error);
      message.error(t('page.user.password.modify_failed'));
    } finally {
      setSubmitting(false);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel();
  };

  return (
    <Modal
      title={t('page.user.password.modify')}
      open={visible}
      onCancel={handleCancel}
      footer={null}
      destroyOnClose
    >
      <Form form={form} onFinish={handleSubmit} layout="vertical" name="modifyPassword">
        <Form.Item
          label={t('page.user.password.username')}
          name="username"
          initialValue={userInfo.username}
        >
          <Input disabled />
        </Form.Item>
        <Form.Item
          label={t('page.user.password.origin')}
          name="originPassword"
          rules={[{ required: true, message: t('page.user.password.origin_required') }]}
        >
          <Input.Password placeholder={t('page.user.password.origin_required')} />
        </Form.Item>
        <Form.Item
          label={t('page.user.password.new')}
          name="newPassword"
          rules={[
            { required: true, message: t('page.user.password.new_required') },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('originPassword') !== value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error(t('page.user.password.not_same_as_origin')));
              },
            }),
          ]}
        >
          <Input.Password placeholder={t('page.user.password.new_required')} />
        </Form.Item>
        <Form.Item
          label={t('page.user.password.confirm_new')}
          name="confirmPassword"
          rules={[
            { required: true, message: t('page.user.password.confirm_required') },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('newPassword') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error(t('page.user.password.confirm_not_match')));
              },
            }),
          ]}
        >
          <Input.Password placeholder={t('page.user.password.confirm_required')} />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" loading={submitting} block>
            {t('page.user.password.submit')}
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ResetPasswordModal; 